package com.exercises;


import java.util.*;

class Exercise54 {
    public static void main(String[] args) {
        int[] a = new int[]{1, 2, 3};
        int[] b = new int[]{4, 5, 6};
//        int[] c = new int[]{7, 8, 9};
        int[][] m = new int[][]{a, b};
        System.out.println(new Exercise54().spiralOrder(m));
    }


    public List<Integer> spiralOrder(int[][] matrix) {
        int x1 = 0, y1 = 0;
        int x2 = matrix.length - 1, y2 = matrix[0].length - 1;
        List<Integer> result = new ArrayList<>();
        while (true) {
            if (x1 > x2 || y1 > y2) {
                break;
            } else if (x1 == x2 || y1 == y2) {
                result.addAll(lap(matrix, x1, y1, x2, y2));
                break;
            } else {
                result.addAll(lap(matrix, x1, y1, x2, y2));
                x1++;
                y1++;
                x2--;
                y2--;
            }
        }
        return result;
    }

    public List<Integer> lap(int[][] matrix, int x1, int y1, int x2, int y2) {
        List<Integer> result = new ArrayList<>();
        if (x1 == x2) {
            for (int i = y1; i <= y2; i++) {
                result.add(matrix[x1][i]);
            }
        } else if (y1 == y2) {
            for (int i = x1; i <= x2; i++) {
                result.add(matrix[i][y1]);
            }
        } else {
            result.add(matrix[x1][y1]);
            int a = x1, b = y1 + 1;
            while (true) {
                if (a == x1 && b < y2) {
                    result.add(matrix[a][b++]);
                } else if (b == y2 && a < x2) {
                    result.add(matrix[a++][b]);
                } else if (a == x2 && b > y1) {
                    result.add(matrix[a][b--]);
                } else if (b == y1 && a > x1) {
                    result.add(matrix[a--][b]);
                }

                if (a == x1 && b == y1) {
                    break;
                }

            }
        }
        return result;
    }

}

